﻿#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QThread>
#include <QMessageBox>
#include <QDebug>
#include <QDir>
#include <QRandomGenerator>
#include "common/Utils.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow),isConnect(false),m_WaveForm_CH1(WaveForm::NONE)
    ,m_WaveForm_CH2(WaveForm::NONE)
{
    ui->setupUi(this);


    /****************ini初始化****************/
    QString documentsPath = QDir::tempPath();

    // 创建名为“XXX”的文件夹
    QString folderName = "DG4020";
    QString folderPath = QDir(documentsPath).filePath(folderName);
    QDir dir(folderPath);

    if (!dir.exists()) {
        if (dir.mkdir(".")) {
            qDebug() << "文件夹创建成功：" << folderPath;
        } else {
            qDebug() << "文件夹创建失败";
        }
    } else {
        qDebug() << "文件夹已存在：" << folderPath;
    }

    // 获取并输出文件夹路径
    qDebug() << "Ini文件夹路径：" << folderPath;
//    QString iniFilePath = QCoreApplication::applicationDirPath() + "/Settings.ini";
    QString iniFilePath = folderPath + "/app_settings.ini";

    m_Settings = new QSettings(iniFilePath,QSettings::IniFormat);



    /*************2.线程初始化******************/
    m_Thread = new QThread();
    m_ModBusTcpWorker = new ModBusTcpWorker(nullptr,false);

    // 将 worker 移动到新线程，并确保在线程结束时删除
    m_ModBusTcpWorker->moveToThread(m_Thread);
    connect(m_Thread, &QThread::finished, m_Thread, &QObject::deleteLater);

    // 当 worker 被删除时，结束线程
    connect(m_ModBusTcpWorker, &QObject::destroyed, m_Thread, &QThread::quit);

    // 获取QCoreApplication的实例
    QCoreApplication *app = QCoreApplication::instance();
    if(app)
    {
        // 确保在应用程序退出时线程已经结束
        connect(app, &QCoreApplication::aboutToQuit, m_Thread, &QThread::quit);
        connect(m_Thread, &QThread::finished, app, &QCoreApplication::quit);
    }

    connect(this,&MainWindow::sig_SetProNameDevType,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetProNameDevType,Qt::QueuedConnection);
    connect(this,&MainWindow::sig_SetIPPort,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetIPPort,Qt::QueuedConnection);
    connect(this,&MainWindow::sig_SetReadStartAddressAndRegisterCount,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetReadStartAddressAndRegisterCount,Qt::QueuedConnection);
    connect(this,&MainWindow::sig_SetWriteStartAddressAndRegisterCount,m_ModBusTcpWorker,&ModBusTcpWorker::slotSetWriteStartAddressAndRegisterCount,Qt::QueuedConnection);
    connect(this,&MainWindow::sig_ConnectionAndLoopReadRegister,m_ModBusTcpWorker,&ModBusTcpWorker::slotStartConnection,Qt::QueuedConnection);
    connect(this,&MainWindow::sig_AddWriteQueue,m_ModBusTcpWorker,&ModBusTcpWorker::slotAddWriteQueue,Qt::QueuedConnection);

    connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_readBoolData,this,&MainWindow::slot_readBoolData,Qt::QueuedConnection);
    connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_readfloatData,this,&MainWindow::slot_readfloatData,Qt::QueuedConnection);
    connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_ConnectionState,this,&MainWindow::slot_ConnectionState,Qt::QueuedConnection);
    connect(m_ModBusTcpWorker,&ModBusTcpWorker::sig_WriteDataQueueFinish,this,&MainWindow::slot_WriteDataQueueFinish,Qt::QueuedConnection);

    //线程开始
    m_Thread->start();

    /*******设置子线程*******/
    //设置设备名称和类型ID 这个类被多次实例化区分使用，本次使用不上
    emit sig_SetProNameDevType("SolidStateDG4020",1);
    emit sig_SetIPPort("192.168.0.170",502);

    QList<int> ReadStartAddressList; //开始地址的列表
    QList<int> ReadRegisterCountList;//开始地址的个数

    // 设置起始地址和寄存器个数  3为保持寄存器
    ReadStartAddressList  << 0 ;
    ReadRegisterCountList << 2 ;

    emit sig_SetReadStartAddressAndRegisterCount(ReadStartAddressList,ReadRegisterCountList,3);

    //连接并开始循环读寄存器
    emit sig_ConnectionAndLoopReadRegister(true);



    /*
    // 创建QFile对象
    QFile file(iniFilePath);
    // 检查文件是否存在
    if (!file.exists())
    {
        // 文件不存在，尝试创建文件
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            m_Settings->setValue("WaveForm_1/Sine","FUNCtion:SHAPe SINusoid");
            m_Settings->setValue("WaveForm_1/Square","FUNCtion:SHAPe SQUare");
            m_Settings->setValue("WaveForm_1/Ramp","FUNCtion:SHAPe RAMP");
            m_Settings->setValue("WaveForm_1/Pulse","FUNCtion:SHAPe PULSe");
            m_Settings->setValue("WaveForm_1/Noise","FUNCtion:SHAPe NOISe");
            m_Settings->setValue("WaveForm_1/Arb","FUNCtion:SHAPe ARB");
            m_Settings->setValue("WaveForm_1/Harmonic","FUNCtion:SHAPe HARMonic");
            file.close();
        }
    }
    */


    ui->textEdit_Address->blockSignals(true);
    ui->textEdit_Address->setText( m_Settings->value("SaveData/Address", "USB0::0x1AB1::0x0641::DG4E224601866::INSTR").toString());
    //_port = m_Settings->value("Communication/Port",502).toUInt();
    ui->textEdit_Address->blockSignals(false);

    // 初始化VISA资源管理器
    status = viOpenDefaultRM(&defaultRM);
    if (status < VI_SUCCESS) {
        qDebug() << "Failed to open default resource manager";
        ui->statusbar->showMessage("打开资源失败！！！",2500);
    }


    /*****************刷新UI*********************/
//    m_Settings->beginGroup("WaveForm");

//    // 获取该组下的所有键
//    QStringList keys = m_Settings->allKeys();

//    // 遍历所有键
//    for (const QString &key : keys) {
//        // 获取键对应的值
//        QVariant value = m_Settings->value(key);

//        // 将键和值添加到QComboBox中
//        ui->cBox_WaveForm->addItem(key, value);
//    }

//    m_Settings->endGroup();
    msgBox.setWindowTitle("提示");
    //msgBox.setText("未连接设备，请先连接");

    msgBox.setIcon(QMessageBox::Warning);

    // 创建 OK 和 Cancel 按钮
    QPushButton *okButton = msgBox.addButton("确认", QMessageBox::AcceptRole);
    QPushButton *cancelButton = msgBox.addButton("取消", QMessageBox::RejectRole);

    // 设置按钮大小
    QSize buttonSize(80, 30); // 宽度100，高度40
    okButton->setFixedSize(buttonSize);
    cancelButton->setFixedSize(buttonSize);

    /************恢复软件的上次记录***************/
    //QString str = m_Settings->value("CurrentRecords/WaveForm_1","NONE").toString();
    m_WaveForm_CH1 = WaveForm::NONE;
    m_WaveForm_CH2 = WaveForm::NONE;
    /*
    if(str == "SINE")
        m_WaveForm = WaveForm::SINE;
    else if(str == "SQUARE")
        m_WaveForm = WaveForm::SQUARE;
    else if(str == "RAMP")
        m_WaveForm = WaveForm::RAMP;
    else if(str == "PULSE")
        m_WaveForm = WaveForm::PULSE;
    else if(str == "NOISE")
        m_WaveForm = WaveForm::NOISE;
    else if(str == "ARB")
        m_WaveForm = WaveForm::ARB;
    else if(str == "HARMONIC")
        m_WaveForm = WaveForm::HARMONIC;
    else if(str == "NONE")
        m_WaveForm = WaveForm::NONE;
    */
    m_timer = new QTimer(this);
    connect(m_timer,&QTimer::timeout,this,&MainWindow::timeoutWatchDog);
}

MainWindow::~MainWindow()
{
    // 关闭设备
    viClose(vi);
    // 关闭资源管理器
    viClose(defaultRM);
    delete ui;
}


void MainWindow::on_btn_Connect_clicked()
{
    if(isConnect)
    {
        // 关闭设备
        viClose(vi);
        // 关闭资源管理器
        //viClose(defaultRM);
        ui->btn_State->setChecked(false);
        ui->btn_Connect->setText("连接");
        isConnect = false;
        ui->statusbar->showMessage("断开连接",2500);
    }
    else
    {
        QString resource = ui->textEdit_Address->toPlainText();
        status = viOpen(defaultRM, resource.toUtf8().constData(), VI_NULL, VI_NULL, &vi);
        if (status < VI_SUCCESS)
        {
            ui->statusbar->showMessage("连接失败",2500);
            ui->btn_State->setChecked(false);
        }
        else
        {
            ui->statusbar->showMessage("连接成功",2500);
            ui->btn_State->setChecked(true);
            ui->btn_Connect->setText("已连接");
            isConnect = true;

            QString scpiCommand = "*IDN?\n";
            ui->textEdit_Command->setText("*IDN?");
            status = viPrintf(vi, scpiCommand.toUtf8().constData());
            if (status < VI_SUCCESS) {
                qDebug() << "Failed to send SCPI command";
            }
            else
            {
                // 接收返回信息
                char buffer[256];
                status = viScanf(vi, "%s", buffer);
                if (status < VI_SUCCESS) {
                    qDebug() << "Failed to read response";
                    ui->statusbar->showMessage("查找设备名称失败",2500);
                    //viClose(vi);
                    return;
                }
                else
                {
                    // 打印返回信息
                    ui->statusbar->showMessage(QString("设备名称:%1 已连接").arg(buffer),2500);
                    qDebug() << "Response from device:" << buffer;
                }
            }

            ViChar ResponseBuffer[256];
            status = viScanf(vi, "%s", ResponseBuffer);
            if (status < VI_SUCCESS) {
                qDebug() << "Failed to read response";
                ui->statusbar->showMessage("获取频率",2500);
                //viClose(vi);
            }
            else
            {
                // 打印返回信息
                QString  ResponseStr = QString(ResponseBuffer);
                ui->textBrowser_Response->setText(ResponseStr);
                ui->statusbar->showMessage(QString("返回消息：%1").arg(ResponseStr),2500);
                qDebug() << "Response:" << ResponseStr;
            }
        }

        /*
        QString scpiCommand = ":SOUR1:FUNC SIN";
        status = viPrintf(vi, scpiCommand.toUtf8().constData());
        if (status < VI_SUCCESS) {
            qDebug() << "Failed to send SCPI command";
        }

        // 设置频率为1kHz
        scpiCommand = ":SOUR1:FREQ 1000";
        status = viPrintf(vi, scpiCommand.toUtf8().constData());
        if (status < VI_SUCCESS) {
            qDebug() << "Failed to set frequency";
        }

        // 设置幅度为2V
        scpiCommand = ":SOUR1:VOLT 2";
        status = viPrintf(vi, scpiCommand.toUtf8().constData());
        if (status < VI_SUCCESS) {
            qDebug() << "Failed to set amplitude";
        }
        */

    }
}


void MainWindow::on_btn_Write_clicked()
{
    if(isConnect)
    {
        QString scpiCommand = QString("%1\n").arg(ui->textEdit_Command_2->toPlainText());
        status = viPrintf(vi, scpiCommand.toUtf8().constData());
        if (status < VI_SUCCESS) {
            qDebug() << "Failed to send WaveForm command";
        }
        else
        {
            // 接收返回信息
            ViChar buffer[256];
            status = viScanf(vi, "%s", buffer);
            if (status < VI_SUCCESS) {
                qDebug() << "Failed to read response";
                ui->statusbar->showMessage("切换波形失败",2500);
                //viClose(vi);
            }
            else
            {
                // 打印返回信息
                QString  ResponseStr = QString(buffer);
                ui->textBrowser_Response->setText(ResponseStr);
                ui->statusbar->showMessage(QString("写入成功返回消息：%1").arg(ResponseStr),2500);
                qDebug() << "Response from device:" << buffer;
            }
        }
    }
}

void MainWindow::on_btn_Sine_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::SINE,1);
    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,1);
    }
}

void MainWindow::on_btn_Square_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::SQUARE,1);

    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,1);
    }
}

void MainWindow::on_btn_Ramp_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::RAMP,1);

    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,1);
    }
}

void MainWindow::on_btn_Pulse_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::PULSE,1);

    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,1);
    }
}

void MainWindow::on_btn_Noise_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::NOISE,1);

    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,1);
    }
}

void MainWindow::on_btn_Arb_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::ARB,1);

    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,1);
    }
}


void MainWindow::on_btn_Hormonic_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::HARMONIC,1);

    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,1);
    }
}


void MainWindow::on_btn_Sine_2_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::SINE,2);

    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,2);
    }
}

void MainWindow::on_btn_Square_2_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::SQUARE,2);

    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,2);
    }
}

void MainWindow::on_btn_Ramp_2_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::RAMP,2);

    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,2);
    }
}

void MainWindow::on_btn_Pulse_2_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::PULSE,2);

    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,2);
    }
}

void MainWindow::on_btn_Noise_2_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::NOISE,2);

    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,2);
    }
}

void MainWindow::on_btn_Arb_2_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::ARB,2);

    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,2);
    }
}

void MainWindow::on_btn_Hormonic_2_clicked()
{
    checkConnected();
    QStringList strList =  GenerateSwtichWaveFormCommand(WaveForm::HARMONIC,2);

    if(strList.size() == 2)
    {
        QString  ResponseStr = setSCPICommand(strList.at(0),strList.at(1));
        if(ResponseStr != "")
            setWaveForm(ResponseStr,2);
    }
}


void MainWindow::checkConnected()//检验是否连接的函数
{
    if(!isConnect)
    {
        msgBox.setText("未连接设备，是否先连接设备？");
        msgBox.setIcon(QMessageBox::Information);
        int ret = msgBox.exec();

        // 根据用户的选择执行操作
        if (ret == QMessageBox::AcceptRole) {
            on_btn_Connect_clicked();
            // 用户点击了 OK 按钮
            // 这里可以放置退出程序的代码
            return;
        }
    }
}

QStringList MainWindow::GenerateSwtichWaveFormCommand(MainWindow::WaveForm waveForm,int chNum)
{
    QString command("");
    QString RespCommand("");//请求状态的指令
    QStringList CommandSet;//发送和查询的指令集合
    switch (chNum)
    {
    case 1:
        if(m_WaveForm_CH1 == waveForm)
            return CommandSet;
        m_WaveForm_CH1 = waveForm;
        switch (m_WaveForm_CH1)
        {
        case MainWindow::WaveForm::SINE:
            //m_Settings->setValue("CurrentRecords/WaveForm","SINE");
            //command = m_Settings->value("WaveForm/Sine").toString();
            //PrintfResponseStr = "Failed to send WaveForm Switch SINE";
            command = ":SOURce1:FUNCtion SINusoid";
            break;
        case MainWindow::WaveForm::SQUARE:
            command = ":SOURce1:FUNCtion SQUare";
            break;
        case MainWindow::WaveForm::RAMP:
            command = ":SOURce1:FUNCtion RAMP";
            break;
        case MainWindow::WaveForm::PULSE:
            command = ":SOURce1:FUNCtion PULSe";
            break;
        case MainWindow::WaveForm::NOISE:
            command = ":SOURce1:FUNCtion NOISe";
            break;
        case MainWindow::WaveForm::ARB:
            command = ":SOURce1:FUNCtion ARB";
            break;
        case MainWindow::WaveForm::HARMONIC:
            command = ":SOURce1:FUNCtion HARMonic";
            break;
        default:
            return CommandSet;
            break;
        }
        RespCommand = ":SOURce1:FUNCtion?";
        break;
    case 2:
        if(m_WaveForm_CH2 == waveForm)
            return CommandSet;
        m_WaveForm_CH2 = waveForm;
        switch (m_WaveForm_CH2)
        {
        case MainWindow::WaveForm::SINE:
            //m_Settings->setValue("CurrentRecords/WaveForm","SINE");
            //command = m_Settings->value("WaveForm/Sine").toString();
            //PrintfResponseStr = "Failed to send WaveForm Switch SINE";
            command = ":SOURce2:FUNCtion SINusoid";
            break;
        case MainWindow::WaveForm::SQUARE:
            command = ":SOURce2:FUNCtion SQUare";
            break;
        case MainWindow::WaveForm::RAMP:
            command = ":SOURce2:FUNCtion RAMP";
            break;
        case MainWindow::WaveForm::PULSE:
            command = ":SOURce2:FUNCtion PULSe";
            break;
        case MainWindow::WaveForm::NOISE:
            command = ":SOURce2:FUNCtion NOISe";
            break;
        case MainWindow::WaveForm::ARB:
            command = ":SOURce2:FUNCtion ARB";
            break;
        case MainWindow::WaveForm::HARMONIC:
            command = ":SOURce2:FUNCtion HARMonic";
            break;
        default:
            return CommandSet;
            break;
        }
        RespCommand = ":SOURce2:FUNCtion?";
        break;
    default:
        break;
    }

    CommandSet << command << RespCommand;
    return  CommandSet;
}

void MainWindow::setWaveForm(QString ResponseStr,int chNum )
{
    switch (chNum) {
    case 1:
    {
        if(ResponseStr == "SIN")
            m_WaveForm_CH1 = WaveForm::SINE;
        else if(ResponseStr == "SQU")
            m_WaveForm_CH1 = WaveForm::SQUARE;
        else if(ResponseStr == "RAMP")
            m_WaveForm_CH1 = WaveForm::RAMP;
        else if(ResponseStr == "PULSE")
            m_WaveForm_CH1 = WaveForm::PULSE;
        else if(ResponseStr == "NOISE")
            m_WaveForm_CH1 = WaveForm::NOISE;
        else if(ResponseStr == "SINC")
            m_WaveForm_CH1 = WaveForm::ARB;
        else if(ResponseStr == "HARMONIC")
            m_WaveForm_CH1 = WaveForm::HARMONIC;
        m_Settings->setValue("CurrentRecords/WaveForm_1",ResponseStr);
    }
        break;

    case 2:
    {
        if(ResponseStr == "SIN")
            m_WaveForm_CH2 = WaveForm::SINE;
        else if(ResponseStr == "SQU")
            m_WaveForm_CH2 = WaveForm::SQUARE;
        else if(ResponseStr == "RAMP")
            m_WaveForm_CH2 = WaveForm::RAMP;
        else if(ResponseStr == "PULSE")
            m_WaveForm_CH2 = WaveForm::PULSE;
        else if(ResponseStr == "NOISE")
            m_WaveForm_CH2 = WaveForm::NOISE;
        else if(ResponseStr == "SINC")
            m_WaveForm_CH2 = WaveForm::ARB;
        else if(ResponseStr == "HARMONIC")
            m_WaveForm_CH2 = WaveForm::HARMONIC;
        m_Settings->setValue("CurrentRecords/WaveForm_2",ResponseStr);
    }
        break;
    default:
        break;
    }

}

QString MainWindow::setSCPICommand(QString sendCommand, QString RespCommand)
{
    QString  returnStr("");//返回的字符串
    ViChar buffer[256];

    ui->textEdit_Command->setText(sendCommand);
    QString scpiCommand = QString("%1\n").arg(sendCommand);//加上换行符

    status = viPrintf(vi, scpiCommand.toUtf8().constData());
    if (status < VI_SUCCESS)
    {
        ui->statusbar->showMessage("发送指令失败",2500);
        viStatusDesc(vi, status, buffer);
        qDebug() << "Failed to send command:" << buffer;
        return returnStr;
    }

    /*****************发送完查询*****************/
    ViChar queryBuffer[256];
    QString queryCommand = QString("%1\n").arg(RespCommand);//加上换行符"
    status = viPrintf(vi, queryCommand.toUtf8().constData());
    if (status < VI_SUCCESS) { // 失败
        viStatusDesc(vi, status, queryBuffer);
        qDebug() << "查询指令发送失败:" << queryBuffer;
    }
    else                       //成功
    {
        ViChar ResponseBuffer[256];
        status = viScanf(vi, "%s", ResponseBuffer);
        if (status < VI_SUCCESS) {
            viStatusDesc(vi, status, ResponseBuffer);
            qDebug() << "查询指令返回失败:"<< ResponseBuffer;
            ui->statusbar->showMessage("查询指令返回失败",2500);
            //viClose(vi);
        }
        else
        {
            // 打印返回信息
            QString  ResponseStr = QString(ResponseBuffer);
            ui->textBrowser_Response->setText(ResponseStr);
            ui->statusbar->showMessage(QString("查询信息：%1").arg(ResponseStr),2500);
            qDebug() << "Response:" << ResponseStr;
            returnStr = ResponseStr;
        }
    }
    return returnStr;
}

void MainWindow::on_btn_Frequency_clicked()//设置频率的按钮
{
    checkConnected();
    float frequency = ui->dSpinBox_Frequency->value() * 1000000;
    QString command = QString(":SOURce1:FREQuency %1").arg(frequency);
    QString queryCommand = ":SOURce1:FREQuency?";//
    setSCPICommand(command,queryCommand);

}
void MainWindow::on_btn_Frequency_2_clicked()
{
    checkConnected();
    float frequency = ui->dSpinBox_Frequency_2->value();
    QString command = QString(":SOURce2:FREQuency %1").arg(frequency);
    QString queryCommand = ":SOURce2:FREQuency?";//
    setSCPICommand(command,queryCommand);
}

//设置幅度
void MainWindow::on_btn_Amplitude_clicked()
{
    checkConnected();
    float Amplitude = ui->dSpinBox_Amplitude->value();
    if (Amplitude < 1.0 || Amplitude > 34.0) {
        qDebug() << "Error: Frequency out of range (1  to 24 dBm).\n";
        return ;
    }
    ViChar buffer[256];
    QString command = QString(":VOLTage %1").arg(Amplitude);
    ui->textEdit_Command->setText(command);
    QString scpiCommand = QString("%1\n").arg(command);//加上换行符

    //status = viPrintf(vi, scpiCommand.toUtf8(), frequency);
    status = viPrintf(vi, scpiCommand.toUtf8().constData());
    if (status < VI_SUCCESS)
    {
        qDebug() << "Failed to read response";
        ui->statusbar->showMessage("设置频率失败",2500);
        viStatusDesc(vi, status, buffer);
        qCritical() << "Failed to send command:" << buffer;
        return;
    }
    else
    {
        // 打印返回信息
        QString  ResponseStr = QString(buffer);
        ui->textBrowser_Response->setText(ResponseStr);
        ui->statusbar->showMessage(QString("写入成功返回消息：%1").arg(ResponseStr),2500);
        qDebug() << "Response from device:" << buffer;
    }

    /*****************发送完查询*****************/
    ViChar queryBuffer[256];
    QString queryCommand = ":VOLTage?\n";//加上换行符
    status = viPrintf(vi, queryCommand.toUtf8().constData());
    if (status < VI_SUCCESS) { // 失败
        viStatusDesc(vi, status, queryBuffer);
        qCritical() << "Failed to send ':FUNCtion?':" << queryBuffer;
    }
    else                       //成功
    {
        ViChar ResponseBuffer[256];
        status = viScanf(vi, "%s", ResponseBuffer);
        if (status < VI_SUCCESS) {
            qDebug() << "Failed to read response";
            ui->statusbar->showMessage("获取幅值",2500);
            //viClose(vi);
        }
        else
        {
            // 打印返回信息
            QString  ResponseStr = QString(ResponseBuffer);
            ui->textBrowser_Response->setText(ResponseStr);
            ui->statusbar->showMessage(QString("返回消息：%1").arg(ResponseStr),2500);
            qDebug() << "Response:" << ResponseStr;
            setWaveForm(ResponseStr);//改枚举的标志
        }
    }
}


//设置幅度的单位
void MainWindow::on_btn_UNIT_clicked()
{
    checkConnected();
    QString command = QString(":SOURce1:VOLTage:UNIT %1").arg(ui->comboBox_UNIT->currentText());
    QString queryCommand = ":SOURce1:VOLTage:UNIT?";//
    setSCPICommand(command,queryCommand);
}

void MainWindow::on_btn_UNIT_2_clicked()
{
    checkConnected();
    QString command = QString(":SOURce2:VOLTage:UNIT %1").arg(ui->comboBox_UNIT_2->currentText());
    QString queryCommand = ":SOURce1:VOLTage:UNIT?";//
    setSCPICommand(command,queryCommand);
}

//设置偏移
void MainWindow::on_btn_Offset_clicked()
{
    checkConnected();
    QString command = QString(":SOURce1:VOLTage:OFFSet %1").arg(ui->dSpinBox_Offset->value());
    QString queryCommand = ":SOURce1:VOLTage:OFFSet?";//
    setSCPICommand(command,queryCommand);
}
void MainWindow::on_btn_Offset_2_clicked()
{
    checkConnected();
    QString command = QString(":SOURce2:VOLTage:OFFSet %1").arg(ui->dSpinBox_Offset->value());
    QString queryCommand = ":SOURce2:VOLTage:OFFSet?";//
    setSCPICommand(command,queryCommand);
}


//开始输出
void MainWindow::on_btn_OutPutOn_clicked()
{
    checkConnected();
    QString command = ":OUTPut1 ON";
    QString queryCommand = ":OUTPut1?";//
    setSCPICommand(command,queryCommand);
}

void MainWindow::on_btn_OutPutOff_clicked()
{
    checkConnected();
    QString command = ":OUTPut1 OFF";
    QString queryCommand = ":OUTPut1?";//
    setSCPICommand(command,queryCommand);
}

void MainWindow::on_btn_OutPutOn_2_clicked()
{
    checkConnected();
    QString command = ":OUTPut2 ON";
    QString queryCommand = ":OUTPut2?";//
    setSCPICommand(command,queryCommand);
}

void MainWindow::on_btn_OutPutOff_2_clicked()
{
    checkConnected();
    QString command = ":OUTPut2 OFF";
    QString queryCommand = ":OUTPut2?";//
    setSCPICommand(command,queryCommand);
}

void MainWindow::on_btn_Impedance_clicked()
{
    checkConnected();
    if(ui->cBox_Impedance->currentText() == "50Ω")
    {
        QString command = ":OUTPut1:IMPedance 50";
        QString queryCommand = ":OUTPut1:IMPedance?";//
        setSCPICommand(command,queryCommand);
    }
    else
    {
        QString command = ":OUTPut1:IMPedance INFINITY";
        QString queryCommand = ":OUTPut1:IMPedance?";//
        setSCPICommand(command,queryCommand);
    }
}

void MainWindow::on_btn_Impedance_2_clicked()
{
    checkConnected();
    if(ui->cBox_Impedance_2->currentText() == "50Ω")
    {
        QString command = ":OUTPut2:IMPedance 50";
        QString queryCommand = ":OUTPut2:IMPedance?";//
        setSCPICommand(command,queryCommand);
    }
    else
    {
        QString command = ":OUTPut2:IMPedance INFINITY";
        QString queryCommand = ":OUTPut2:IMPedance?";//
        setSCPICommand(command,queryCommand);
    }
}


void MainWindow::slot_readBoolData(int MsgId, QList<bool> data)
{

}

void MainWindow::slot_readfloatData(int MsgId, QList<float> data)
{
    switch (MsgId) {
    case 300:
        if(!data.isEmpty())
        {
            float fValue = data.at(0);
            ui->doubleSpinBox_VEpower->setValue(fValue);

            long double  ld_Vol = 0.0002585999448563789*fValue*fValue*fValue+0.008548964337510706*fValue*fValue+0.13274596145854*fValue+0.8791631256907083;
            ui->doubleSpinBox_Vol->setValue(ld_Vol);
        }
        break;
    default:
        break;
    }
}

void MainWindow::slot_ConnectionState(bool isConnectionState)
{

}

void MainWindow::slot_WriteDataQueueFinish()
{

}

void MainWindow::timeoutWatchDog()
{
    if( ui->doubleSpinBox_VEpower->value() >= ui->doubleSpinBox_SetVEP->value())
    {
        m_timer->stop();
        return;
    }

    double fAmpValue = ui->dSpinBox_Amplitude->value();
    fAmpValue += 0.1;//幅值0.1的递增增加
    ui->dSpinBox_Amplitude->setValue(fAmpValue);
    on_btn_Amplitude_clicked();
    //发送模式
    float currentPower = static_cast<float>(ui->doubleSpinBox_VEpower->value());

    // 生成0.1到0.3之间的随机数
    currentPower += QRandomGenerator::global()->generateDouble() * 0.2 + 0.1;

    QList<quint16> sendData;
    sendData << floatToQuint16(currentPower);
    WriteData* writeData1 = new WriteData(0,sendData.size(),sendData);
    emit sig_AddWriteQueue(writeData1);



}


//开始递增
void MainWindow::on_btn_Inc_clicked(bool checked)
{
    if(checked)
    {
        checkConnected();
        if(!m_timer->isActive())
            m_timer->start(ui->spinBox_MSec->value());
    }
    else
    {
        if(m_timer->isActive())
            m_timer->stop();
    }
}

